package com.alogic.xscript.ldap;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.*;
import org.apache.commons.lang3.StringUtils;
import javax.naming.NamingException;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;


/**
 * LDAP修改密码
 */
public class LDAPUpdatePassword extends LDAPConnection.Operation {

    /**
     * 新增条目的dn
     */
    protected String $dn;

    /**
     * 密码
     */
    protected String $password;

    /**
     * 密码的属性id
     */
    protected String pwdAttrId = "userPassword";

    /**
     * 结果id
     */
    protected String id;

    public LDAPUpdatePassword(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $dn = PropertiesConstants.getRaw(p,"dn",$dn);
        $password = PropertiesConstants.getRaw(p,"pwd","");

        id = PropertiesConstants.getString(p,"id","",true);
        pwdAttrId = PropertiesConstants.getString(p,"pwdAttrId","userPassword",true);
    }

    @Override
    protected void onExecute(DirContext dirContext, XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String dn = PropertiesConstants.transform(ctx,$dn,"");
        if (StringUtils.isEmpty(dn)){
            log("The dn is null,operation is ignored.",LOG_WARNING,ctx);
            return ;
        }

        try {
            String password = PropertiesConstants.transform(ctx,$password,"");
            if (StringUtils.isNotEmpty(password)) {
                Object exist = dirContext.lookup(dn);
                if (exist != null) {
                    BasicAttributes attrs = new BasicAttributes();
                    attrs.put(pwdAttrId,password);
                    dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
                }
            }
            if (StringUtils.isNotEmpty(id)){
                ctx.SetValue(id,"true");
            }
        }catch (NamingException ex){
            log("Can not create dir context:" + ex.toString(),LOG_ERROR,ctx);
            if (StringUtils.isNotEmpty(id)){
                ctx.SetValue(id,ex.getClass().getName());
                ctx.SetValue(id + ".reason",ex.toString(true));
            }
        }
    }
}
